All files / src/app/user/profile page.tsx

0% Statements 0/188
0% Branches 0/190
0% Functions 0/33
0% Lines 0/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
'use client';
 
import { useEffect, useMemo, useState, Suspense } from 'react';
import Link from 'next/link';
import { usePathname, useSearchParams } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { EmptyState } from '@/components/ui/empty-state';
import LogoutButton from '@/components/auth/LogoutButton';
import { UserRoute } from '@/components/auth/ProtectedRoute';
import ModernUserSidebar from '@/components/user/ModernUserSidebar';
import { useAuth } from '@/contexts/AuthContext';
import { useBannedRedirect } from '@/hooks/useBannedRedirect';
import { ROUTES } from '@/constants/app';
import { apiErrorMessage, cn } from '@/lib/utils';
import { contentService, userProfileService } from '@/services';
import type { UserProfile } from '@/types';
import { toast } from 'sonner';
import {
  ShieldCheck,
  UserRound,
  Mail,
  CalendarClock,
  Crown,
  Lock,
  Home,
  Tv,
  Film,
  Clapperboard,
  Search,
  Stars,
  Wand2,
  Clock,
  Sparkles,
  MonitorSmartphone
} from 'lucide-react';
 
function ProfileLoading() {
  const { t } = useTranslation();
  return <div className="p-6 text-slate-400">{t('common.loading')}</div>;
}
 
const infoBadgeStyles =
  'rounded-full bg-slate-900/70 px-3 py-1 text-xs text-slate-300 border border-slate-800';
 
function ProfilePageInner() {
  const { t } = useTranslation();
  const { user } = useAuth();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const queryClient = useQueryClient();
  const [emailDraft, setEmailDraft] = useState('');
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
 
  useBannedRedirect();
 
  const { data: profileData, isLoading } = useQuery({
    queryKey: ['user-profile'],
    queryFn: async () => {
      const result = await userProfileService.getProfile();
      if (result.success && result.data) {
        return result.data;
      }
      throw new Error(apiErrorMessage(result.error, t('products.errors.loadProfileFailed')));
    }
  });
 
  useEffect(() => {
    if (profileData?.email) {
      setEmailDraft(profileData.email);
    } else if (user?.email) {
      setEmailDraft(user.email);
    }
  }, [profileData?.email, user?.email]);
 
  const updateProfile = useMutation({
    mutationFn: async () => {
      const result = await userProfileService.updateProfile({
        email: emailDraft.trim() || null
      });
      if (!result.success || !result.data) {
        throw new Error(
          apiErrorMessage(result.error, t('profile.updateFailed')),
        );
      }
      return result.data;
    },
    onSuccess: (updatedProfile) => {
      toast.success(t('user.profile.update.success'));
      queryClient.setQueryData<UserProfile>(['user-profile'], updatedProfile);
    },
    onError: (error: unknown) => {
      const message =
        error instanceof Error
          ? error.message
          : t('user.profile.update.error');
      toast.error(message);
    }
  });
 
  const changePassword = useMutation({
    mutationFn: async () => {
      const result = await userProfileService.changePassword({
        current_password: currentPassword,
        new_password: newPassword
      });
      if (!result.success || !result.data) {
        throw new Error(
          apiErrorMessage(
            result.error,
            t('profile.updatePasswordFailed'),
          ),
        );
      }
      return result.data;
    },
    onSuccess: () => {
      toast.success(t('user.profile.password.success'));
      setCurrentPassword('');
      setNewPassword('');
    },
    onError: (error: unknown) => {
      const message =
        error instanceof Error
          ? error.message
          : t('user.profile.password.error');
      toast.error(message);
    }
  });
 
  // Timestamps and profile access
  const profile = profileData;
  const createdAt = profile?.created_at ? new Date(profile.created_at) : null;
  const expiresAt = profile?.expires_at ? new Date(profile.expires_at) : null;
 
  // Load all categories (id -> object mapping) to resolve user subscriptions
  const { data: allCategories = [] } = useQuery({
    queryKey: ['categories', 'all'],
    staleTime: 5 * 60 * 1000,
    queryFn: async () => {
      const res = await contentService.getCategories();
      if (res.success && res.data) return res.data;
      return [];
    }
  });
 
  // Normalize user subscribed categories (can be array of objects or array of IDs)
  const userCategoryObjs = useMemo(() => {
    // Normalize from multiple possible shapes:
    // - user.subscribed_categories: Array<{id,name,category_type}> OR Array<number>
    // - profile.subscribed_categories: Array<number>
    // Fallback to names if present even when IDs can't be resolved.
    const result: Array<{ id: number; name: string; category_type: string }> =
      [];
 
    const pushUnique = (cat?: {
      id?: number;
      name?: string;
      category_type?: string;
    } | null) => {
      if (!cat) return;
      const id = Number(cat.id ?? 0);
      const name = String(cat.name ?? cat.category_type ?? '').trim();
      const type = String(cat.category_type ?? cat.name ?? '').trim();
      if (!name && !type) return;
      const key = (type || name).toLowerCase();
      if (result.find((x) => (x.category_type || x.name).toLowerCase() === key))
        return;
      result.push({
        id: Number.isFinite(id) && id > 0 ? id : 0,
        name: name || type,
        category_type: type || name
      });
    };
 
    // 1) Try direct from user (objects or IDs)
    const direct = (user as any)?.subscribed_categories as Array<any> | undefined;
    if (Array.isArray(direct) && direct.length) {
      // If they are objects, push directly
      if (typeof direct[0] === 'object') {
        direct.forEach((c) => pushUnique(c));
      } else {
        // They are IDs, resolve via allCategories if available
        const ids = direct as number[];
        ids.forEach((id) => {
          const found = allCategories.find((c: any) => c.id === id);
          if (found) pushUnique(found);
        });
      }
    }
 
    // 2) If still empty, use profile IDs
    if (result.length === 0) {
      const ids = (profile as any)?.subscribed_categories as number[] | undefined;
      if (ids && ids.length && allCategories.length) {
        ids.forEach((id) => {
          const found = allCategories.find((c: any) => c.id === id);
          if (found) pushUnique(found);
        });
      }
    }
 
    return result;
  }, [user?.subscribed_categories, (profile as any)?.subscribed_categories, allCategories]);
 
  // Build sidebar menu based on subscriptions. Keep Inicio and Buscar at ends.
  const menuItems = useMemo(() => {
    type MenuItem = { typeKey: string; label: string; href: string; icon: any; basePath: string };
    const add = new Map<string, MenuItem>();
 
    const byType = (typ: string): MenuItem | null => {
      const typeLower = (typ || '').toLowerCase();
      if (typeLower === 'tv') {
        return {
          typeKey: 'tv',
          label: t('user.menu.liveTv'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=live`,
          icon: Tv,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      if (typeLower === 'vod' || typeLower === 'movies' || typeLower === 'movie') {
        return {
          typeKey: 'vod',
          label: t('user.menu.movies'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=movies`,
          icon: Film,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      if (typeLower === 'series' || typeLower === 'shows' || typeLower === 'show') {
        return {
          typeKey: 'series',
          label: t('user.menu.series'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=shows`,
          icon: Clapperboard,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      if (typeLower === 'kids') {
        return {
          typeKey: 'kids',
          label: t('user.menu.kids'),
          href: `${ROUTES.CONTENT.BROWSE}?category=Kids`,
          icon: Stars,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      if (typeLower === 'anime') {
        return {
          typeKey: 'anime',
          label: t('user.menu.anime'),
          href: `${ROUTES.CONTENT.BROWSE}?category=Anime`,
          icon: Wand2,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      if (typeLower === 'events' || typeLower === 'event') {
        return {
          typeKey: 'events',
          label: t('user.menu.events'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=events`,
          icon: Clock,
          basePath: ROUTES.CONTENT.BROWSE
        };
      }
      return null;
    };
 
    for (const c of userCategoryObjs) {
      const mi = byType(c.category_type || '');
      if (mi) add.set(mi.typeKey, mi);
    }
 
    const weight: Record<string, number> = {
      vod: 10,
      tv: 20,
      series: 30,
      kids: 40,
      anime: 50,
      events: 55
    };
    const subs = Array.from(add.values()).sort(
      (a, b) => (weight[a.typeKey] ?? 999) - (weight[b.typeKey] ?? 999),
    );
 
    const homeItem: MenuItem = {
      typeKey: 'home',
      label: t('user.menu.home'),
      href: ROUTES.USER.BASE,
      icon: Home,
      basePath: ROUTES.USER.BASE
    };
    const searchItem: MenuItem = {
      typeKey: 'search',
      label: t('user.menu.search'),
      href: ROUTES.CONTENT.SEARCH,
      icon: Search,
      basePath: ROUTES.CONTENT.SEARCH
    };
 
    // Fallback: show a full default set while user subscriptions are loading or unavailable
    if (!subs.length) {
      const defaults: MenuItem[] = [
        {
          typeKey: 'tv',
          label: t('user.menu.liveTv'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=live`,
          icon: Tv,
          basePath: ROUTES.CONTENT.BROWSE
        },
        {
          typeKey: 'vod',
          label: t('user.menu.movies'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=movies`,
          icon: Film,
          basePath: ROUTES.CONTENT.BROWSE
        },
        {
          typeKey: 'series',
          label: t('user.menu.series'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=shows`,
          icon: Clapperboard,
          basePath: ROUTES.CONTENT.BROWSE
        },
        {
          typeKey: 'kids',
          label: t('user.menu.kids'),
          href: `${ROUTES.CONTENT.BROWSE}?category=Kids`,
          icon: Stars,
          basePath: ROUTES.CONTENT.BROWSE
        },
        {
          typeKey: 'anime',
          label: t('user.menu.anime'),
          href: `${ROUTES.CONTENT.BROWSE}?category=Anime`,
          icon: Wand2,
          basePath: ROUTES.CONTENT.BROWSE
        },
        {
          typeKey: 'events',
          label: t('user.menu.events'),
          href: `${ROUTES.CONTENT.BROWSE}?tab=events`,
          icon: Clock,
          basePath: ROUTES.CONTENT.BROWSE
        },
      ];
      return [homeItem, ...defaults, searchItem];
    }
 
    return [homeItem, ...subs, searchItem];
  }, [t, userCategoryObjs, ROUTES.CONTENT.BROWSE, ROUTES.CONTENT.SEARCH, ROUTES.USER.BASE]);
 
  const usernameLabel = useMemo(
    () => user?.username || t('user.dashboard.guest'),
    [t, user?.username],
  );
 
  const statusLabel = useMemo(() => {
    if (!profile) return t('user.profile.status.unknown');
    if (!profile.active) return t('user.profile.status.banned');
    if (!profile.expires_at)
      return t('user.profile.status.noExpiry');
    if (expiresAt && expiresAt.getTime() < Date.now()) {
      return t('user.profile.status.expired');
    }
    return t('user.profile.status.active');
  }, [profile, expiresAt, t]);
 
  // Active state for sidebar items
  const isItemActive = (itemHref: string, basePath: string) => {
    let isActive = false;
    const baseActive =
      pathname === basePath || pathname.startsWith(`${basePath}/`);
 
    if (basePath === ROUTES.CONTENT.BROWSE) {
      const currentTab = (searchParams.get('tab') || '').toLowerCase();
      const currentCategory = (searchParams.get('category') || '').toLowerCase();
 
      let itemTab = '';
      let itemCategory = '';
      try {
        const u = new URL(itemHref, 'https://local');
        itemTab = (u.searchParams.get('tab') || '').toLowerCase();
        itemCategory = (u.searchParams.get('category') || '').toLowerCase();
      } catch {
        // ignore
      }
 
      if (itemTab) {
        isActive = pathname === ROUTES.CONTENT.BROWSE && currentTab === itemTab;
      } else if (itemCategory) {
        isActive =
          pathname === ROUTES.CONTENT.BROWSE && currentCategory === itemCategory;
      } else {
        isActive = false;
      }
    } else {
      isActive = baseActive;
    }
    return isActive;
  };
 
  // Translate sidebar menu labels at render-time to the "user.menu.*" namespace
  const tMenu = (label: string) => {
    const l = (label || '').toLowerCase().trim();
    let key = 'custom';
    if (l === 'home') key = 'home';
    else if (l.includes('tv')) key = 'liveTv';
    else if (l === 'movies' || l === 'movie') key = 'movies';
    else if (l === 'series' || l === 'shows' || l === 'show') key = 'series';
    else if (l === 'kids' || l === 'children') key = 'kids';
    else if (l === 'anime') key = 'anime';
    else if (l === 'events' || l === 'event') key = 'events';
    else if (l === 'search') key = 'search';
    return t(`user.menu.${key}`);
  };
 
  return (
    <UserRoute>
      <div className="min-h-screen bg-slate-950 text-white">
        {/* Main content */}
        <main className="relative overflow-x-hidden pb-24 h-full">
          <div className="mx-auto flex w-full max-w-5xl flex-col gap-10 px-6 py-10 sm:px-10">
            <header className="space-y-3">
              <Badge
                variant="secondary"
                className="bg-white/10 text-xs uppercase tracking-wide text-white"
              >
                {t('user.profile.badge')}
              </Badge>
              <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
                <div>
                  <h1 className="text-3xl font-semibold tracking-tight sm:text-4xl">
                    {t('user.profile.title')}
                  </h1>
                  <p className="text-sm text-slate-300">
                    {t('user.profile.subtitle')}
                  </p>
                </div>
                <Badge
                  variant="outline"
                  className={cn(
                    'border-slate-800 px-4 py-2',
                    profile?.active
                      ? 'text-green-200 border-green-400/40 bg-green-400/10'
                      : 'text-red-200 border-red-400/40 bg-red-400/10',
                  )}
                >
                  {statusLabel}
                </Badge>
              </div>
            </header>
 
            {isLoading ? (
              <div className="py-20">
                <EmptyState
                  title={t('user.common.loading')}
                  description={t('user.profile.loadingDescription')}
                />
              </div>
            ) : null}
 
            {!isLoading && !profile ? (
              <div className="py-20">
                <EmptyState
                  title={t('user.profile.noDataTitle')}
                  description={t('user.profile.noDataDescription')}
                />
              </div>
            ) : null}
 
            {profile ? (
              <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
                <div className="space-y-6">
                  {/* Basic info */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-lg text-white">
                        <UserRound className="h-5 w-5 text-blue-300" />
                        {t('user.profile.info.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4 text-sm text-slate-300">
                      <div className="grid gap-4 sm:grid-cols-2">
                        <div>
                          <p className="text-xs uppercase tracking-wide text-slate-500">
                            {t('user.profile.info.username')}
                          </p>
                          <p className="mt-1 text-base text-white">
                            {profile.username}
                          </p>
                        </div>
                        <div>
                          <p className="text-xs uppercase tracking-wide text-slate-500">
                            {t('user.profile.info.role')}
                          </p>
                          <p className="mt-1 text-base text-white capitalize">
                            {profile.role}
                          </p>
                        </div>
                        <div>
                          <p className="text-xs uppercase tracking-wide text-slate-500">
                            {t('user.profile.info.createdAt')}
                          </p>
                          <p className="mt-1 text-base text-white">
                            {createdAt
                              ? createdAt.toLocaleDateString()
                              : t('user.profile.info.unknown')}
                          </p>
                        </div>
                        <div>
                          <p className="text-xs uppercase tracking-wide text-slate-500">
                            {t('user.profile.info.expiresAt')}
                          </p>
                          <p className="mt-1 text-base text-white">
                            {expiresAt
                              ? expiresAt.toLocaleDateString()
                              : t('user.profile.info.noExpiry')}
                          </p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
 
                  {/* Contact */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-lg text-white">
                        <Mail className="h-5 w-5 text-blue-300" />
                        {t('user.profile.contact.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <label
                          htmlFor="email"
                          className="text-xs uppercase tracking-wide text-slate-500"
                        >
                          {t('user.profile.contact.emailLabel')}
                        </label>
                        <Input
                          id="email"
                          type="email"
                          value={emailDraft}
                          onChange={(event) => setEmailDraft(event.target.value)}
                          placeholder={t('user.profile.contact.emailPlaceholder')}
                          className="bg-slate-950/50 text-white placeholder:text-slate-500"
                        />
                      </div>
                      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <p className="text-xs text-slate-500">
                          {t('user.profile.contact.hint')}
                        </p>
                        <Button
                          onClick={() => updateProfile.mutate()}
                          disabled={updateProfile.isPending}
                          className="sm:w-auto"
                        >
                          {updateProfile.isPending
                            ? t('user.profile.contact.saving')
                            : t('user.profile.contact.save')}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
 
                  {/* Password */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-lg text-white">
                        <Lock className="h-5 w-5 text-blue-300" />
                        {t('user.profile.password.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="grid gap-4 sm:grid-cols-2">
                        <div className="space-y-2">
                          <label
                            htmlFor="current-password"
                            className="text-xs uppercase tracking-wide text-slate-500"
                          >
                            {t('user.profile.password.current')}
                          </label>
                          <Input
                            id="current-password"
                            type="password"
                            value={currentPassword}
                            onChange={(event) =>
                              setCurrentPassword(event.target.value)
                            }
                            placeholder={t('user.profile.password.currentPlaceholder')}
                            className="bg-slate-950/50 text-white placeholder:text-slate-500"
                          />
                        </div>
                        <div className="space-y-2">
                          <label
                            htmlFor="new-password"
                            className="text-xs uppercase tracking-wide text-slate-500"
                          >
                            {t('user.profile.password.new')}
                          </label>
                          <Input
                            id="new-password"
                            type="password"
                            value={newPassword}
                            onChange={(event) =>
                              setNewPassword(event.target.value)
                            }
                            placeholder={t('user.profile.password.newPlaceholder')}
                            className="bg-slate-950/50 text-white placeholder:text-slate-500"
                          />
                        </div>
                      </div>
                      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <p className="text-xs text-slate-500">
                          {t('user.profile.password.hint')}
                        </p>
                        <Button
                          onClick={() => changePassword.mutate()}
                          disabled={changePassword.isPending}
                          className="sm:w-auto"
                        >
                          {changePassword.isPending
                            ? t('user.profile.password.saving')
                            : t('user.profile.password.save')}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </div>
 
                {/* Right column */}
                <div className="space-y-6">
                  {/* Plan state */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-sm text-white">
                        <ShieldCheck className="h-4 w-4 text-blue-300" />
                        {t('user.profile.plan.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-3 text-xs text-slate-400">
                      <div className={infoBadgeStyles}>
                        {t('user.profile.plan.devices', {
                          count: profile.device_count,
                          max: profile.max_devices
                        })}
                      </div>
                      <div className={infoBadgeStyles}>
                        {t('user.profile.plan.role', {
                          role: profile.role
                        })}
                      </div>
                      <div className={infoBadgeStyles}>
                        {expiresAt
                          ? t('user.profile.plan.expires', {
                            date: expiresAt.toLocaleDateString()
                          })
                          : t('user.profile.plan.withoutExpiry')}
                      </div>
                    </CardContent>
                  </Card>
 
                  {/* Enabled categories (now resolved) */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-sm text-white">
                        <Crown className="h-4 w-4 text-amber-300" />
                        {t('user.profile.categories.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent>
                      {userCategoryObjs.length ? (
                        <div className="flex flex-wrap gap-2">
                          {userCategoryObjs.map((category, index) => (
                            <Badge
                              key={`${category.id || category.name}-${index}`}
                              variant="outline"
                              className="border-slate-800 bg-slate-950/60 text-slate-200"
                            >
                              {category.name}
                            </Badge>
                          ))}
                        </div>
                      ) : (
                        <p className="text-xs text-slate-500">
                          {t('user.profile.categories.empty')}
                        </p>
                      )}
                    </CardContent>
                  </Card>
 
                  {/* Quick actions */}
                  <Card className="rounded-lg border-slate-900 bg-slate-900/60">
                    <CardHeader>
                      <CardTitle className="flex items-center gap-3 text-sm text-white">
                        <CalendarClock className="h-4 w-4 text-blue-300" />
                        {t('user.profile.actions.title')}
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="flex flex-col gap-3 text-xs text-slate-400">
                      <a
                        href={ROUTES.USER.DEVICES}
                        className="inline-flex items-center justify-start gap-2 border border-slate-800 bg-slate-950/60 text-slate-200 hover:border-blue-500/40 hover:text-white rounded-md px-3 py-2 text-sm font-medium transition-colors"
                      >
                        {t('user.profile.actions.manageDevices')}
                      </a>
                      <a
                        href={ROUTES.USER.BASE}
                        className="inline-flex items-center justify-start gap-2 border border-slate-800 bg-slate-950/60 text-slate-200 hover:border-blue-500/40 hover:text-white rounded-md px-3 py-2 text-sm font-medium transition-colors"
                      >
                        {t('user.profile.actions.exploreContent')}
                      </a>
                      <a
                        href={ROUTES.REDEEM}
                        className="inline-flex items-center justify-start gap-2 border border-slate-800 bg-slate-950/60 text-slate-200 hover:border-blue-500/40 hover:text-white rounded-md px-3 py-2 text-sm font-medium transition-colors"
                      >
                        {t('user.profile.actions.extendMembership')}
                      </a>
                    </CardContent>
                  </Card>
 
 
                </div>
              </div>
            ) : null}
          </div>
        </main>
      </div>
    </UserRoute>
  );
}
export default function ProfilePage() {
  return (
    <Suspense fallback={<ProfileLoading />}>
      <ProfilePageInner />
    </Suspense>
  );
}